import { renderToNodeStream } from '@vue/server-renderer';
import { Controller } from 'egg';
import { pipeline } from 'stream/promises';
import { createSSRApp } from 'vue';

function splitIdAndUuid(str = '') {
  const result = { id: -1, uuid: '' };
  if (!str) return result;
  const firstDashIndex = str.indexOf('-');
  if (firstDashIndex < 0) return result;
  result.id = parseInt(str.slice(0, firstDashIndex));
  result.uuid = str.slice(firstDashIndex + 1);
  return result;
}

export default class HomeController extends Controller {
  public async index() {
    const { ctx } = this;
    const vueApp = createSSRApp({
      data: () => ({ msg: 'hello' }),
      template: '<h1>{{ msg }}</h1>',
    });
    const stream = await renderToNodeStream(vueApp);
    ctx.status = 200;
    await pipeline(stream, ctx.res);
  }

  async renderH5Page() {
    const { ctx } = this;
    const { idAndUuid } = ctx.params;
    const query = splitIdAndUuid(idAndUuid);
    try {
      const pageData = await this.service.util.renderToPageData(query);
      await ctx.render('page.nj', pageData);
    } catch (e) {
      console.log(e);
      ctx.helper.error({ ctx, errorType: 'h5WorkNotExistError' });
    }
  }
}
